<template>
  <div style="position: relative;">
    <!--<x-header title="购物车" style="background-color: #000;"><a slot="right"></a></x-header>-->
    <div style="position: fixed;">
      <img src="../../../assets/images/index_bg.png" style="width: 100%;height:130px;">
    </div>
    <div class="list">
      <div class="company" v-for="v in foodList">
        <h5 class="company-title" @click="toShop(v.shoppingCartList[0])"><i class="iconfont icon-dianpu"></i>{{v.company_name}}</h5>
        <div class="foodItem" v-for="(v1,index) in v.shoppingCartList">
          <div class="item-input">
            <icon type="circle" v-if="checkedIds.indexOf(v1.id)<0"></icon>
            <icon type="success" v-if="checkedIds.indexOf(v1.id)>=0"></icon>
            <input type="checkbox" v-model="checkedIds" :value="v1.id" :id="v1.id" style="width: 1rem;vertical-align: middle;">
          </div>
          <div class="item-img">
            <img :src="config1.fileUrl+v1.img_url+'?x-oss-process=image/resize,w_60,h_60'" alt="">
          </div>
          <div class="item-text">
            <div class="name">
              <div class="name-left">
                <label :for="v1.id">{{v1.goods_name}}</label>
                <p v-show="v1.norms.norm">规格：{{v1.norms.norm}}</p>
              </div>
              <div class="name-right">
                <span class="remove" @click="remove(v1)"><i class="fa fa-trash"></i></span>
              </div>
            </div>
            <div class="name-bottom">
              <div class="price">
                ￥<span>{{(v1.norms.price*1).toFixed(2)}}</span>
              </div>
              <div class="num">
                <x-number title="" v-model="v1.num" :min="0" @on-change="numChange(v1)" style="padding:0;" width="30px"></x-number>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div style="height: 7rem;"></div>
    <!--底部计算框-->
    <div class="bottomCalc">
      <div><check-icon :value.sync="demo1" @click.native="checkAll">全选</check-icon></div>
      <div class="cal">
        <span>合计：<span class="calc">￥{{totalPrice.toFixed(2)}}</span></span>
        <span class="btn" @click="goOrder">结算</span>
        <!--<x-button mini type="warn" style="margin: 0 0 0 1rem;">结算</x-button>-->
      </div>
    </div>
    <div v-transfer-dom>
      <popup v-model="isStore" height="100%" style="background: #fbf9fe">
        <vTitle page="2" @transferUser="back2"></vTitle>
        <vStore v-if="isStore" v-bind:text="text" v-bind:type="type"></vStore>
      </popup>
    </div>
    <toast v-model="showPositionValue" type="text" :time="800" is-show-mask :text="toastMsg" :position="position"></toast>
  </div>
</template>

<script>
    import { Popup } from 'vux'
    import vTitle from '../view1/Title'
    import vStore from '../view1/Store'
    export default {
      name: "Cart",
      components: {
         Popup, vTitle, vStore
      },
      data() {
        return {
          foodList: [],

          checkedIds: [], // 选择的商品ids
          totalPrice: 0,

          demo1: false,

          showPositionValue: false, // Toast提示
          position: 'default',
          toastMsg: '',
          isStore:false,
        }
      },
      watch:{
        checkedIds(newv){
          this.calcTotal();
        },
        demo1(newv){
          // this.checkAll();
        },
      },
      methods: {
        // 信息提示
        msg(str){
          this.showPositionValue = true;
          this.position = 'middle';
          this.toastMsg = (str);
        },
        toShop(text){
          this.text = text
          this.type = 2
          this.isStore = true
        },
        back2(msg){
          this.isStore = msg
        },
        // 获取购物车商品
        getFoodsList() {
          this.$vux.loading.show();
          this.config1.post('/purchasers/app/shoppingCart/findBySupply', {}).then(res => {
            this.$vux.loading.hide();
            if (res.data.code === '0') {
              this.foodList = res.data.shoppingCartSupplyList;
              this.foodList.forEach(it => {
                it.shoppingCartList.forEach(item => {
                  item.norms = JSON.parse(item.norms);
                })
              });
              this.calcTotal();
            } else {
              this.msg(this.config1.handleError(res.data));
            }
          })
        },
        // 计算选择的商品总价
        calcTotal(){
          this.totalPrice = 0;
          let count = 0;
          this.foodList.forEach(it=>{
            it.shoppingCartList.forEach(item=>{
              if(this.checkedIds.indexOf(item.id)>=0){
                this.totalPrice += item.norms.price*item.num;
              }
              count +=1;
            })
          });
          if(this.checkedIds.length>0&&this.checkedIds.length===count){
            this.demo1 = true;
          }else{
            this.demo1 = false;
          }
        },
        // 全选商品
        checkAll(){
          // let bol = e.target.checked;
          if(this.demo1){
            this.checkedIds = [];
            this.foodList.forEach(it=>{
              it.shoppingCartList.forEach(item=>{
                this.checkedIds.push(item.id);
              })
            })
          }else{
            this.checkedIds = [];
          }
        },
        // 加/减商品
        numChange(v) {
          this.$vux.loading.show();
          this.config1.post('/purchasers/app/shoppingCart/update', {
            'shoppingCart.id': v.id,
            'shoppingCart.norms': JSON.stringify(v.norms),
            'shoppingCart.num': v.num,
          }).then(res => {
            this.$vux.loading.hide();
            if (res.data.code === '0') {
              this.msg(res.data.message);
              this.getFoodsList();
            } else {
              this.msg(this.config1.handleError(res.data));
            }
          });
        },
        // 移除
        remove(v) {
          let self = this;
          this.$vux.confirm.show({
            title: '移除',
            content: '确认从购物车删除？',
            onConfirm () {
              self.$vux.loading.show();
              self.config1.post('/purchasers/app/shoppingCart/remove', {id: v.id}).then(res => {
                self.$vux.loading.hide();
                if (res.data.code === '0') {
                  self.msg(res.data.message);
                  self.getFoodsList();
                  bus.$emit('addFood','msg')
                } else {
                  self.msg(self.config1.handleError(res.data));
                }
              })
            }
          });
        },
        // 清空购物车
        clearCart(){
          this.$vux.loading.show();
          this.config1.post('/purchasers/app/shoppingCart/emptyCart', {}).then(res=>{
            this.$vux.loading.hide();
            if (res.data.code === '0') {
              this.msg(res.data.message);
              this.getFoodsList();
              bus.$emit('addFood','msg')
            } else {
              this.msg(this.config1.handleError(res.data));
            }
          })
        },
        // 构造订单对象
        buildOrder(){
          let arr = [];
          this.foodList.forEach(it=>{
            // it.is_open_invoice = '0';
            let arr1 = [];
            it.shoppingCartList.forEach(item=>{
              if(this.checkedIds.indexOf(item.id)>=0){
                arr1.push(item);
              }
            });
            arr.push({
              id: it.id,
              company_name: it.company_name,
              is_open_invoice: '0',
              shoppingCartList: arr1
            });
          });
          return arr;
        },
        // 去下单
        goOrder(){
          let order = this.buildOrder();
          if(!this.checkedIds.length) {
            this.msg('请选择商品');
            return;
          }
          this.$router.push({path: '/project1/view2/make-order', query: {order: JSON.stringify(order), sign: 'cart'}});
        },
      },
      mounted() {
        this.getFoodsList();
      }
    }
</script>

<style scoped lang="less">
  @import "../../../assets/css/font_975465_4qn59qnejbp/iconfont.css";
  .list {
    width: 100%;
    margin: 1rem auto;
    position: absolute;
    text-align: left;
    padding-bottom:80px;
    .company {
      border-radius: 8px;
      box-shadow: 0 0 5px 0 silver;
      background: #fff;
      margin: 1rem;
      .company-title {
        padding:0.5rem;
        .iconfont{
          color:#33bb99;
          padding-right:5px;
          font-size:0.9rem;
          font-weight: normal;
        }
      }
      .foodItem {
        font-size: 0.8rem;
        clear: both;
        padding: 1rem 1rem 1rem 0.5rem;
        /*height:65px;*/
        border-top: 1px solid #33bb99;
        display: flex;
        .item-input{
          width:10%;
          padding-top: 20px;
          padding-left:0;
          position: relative;
          input{
            position: absolute;
            width: 100%;
            height: 100%;
            top:0;
            left: 0;
            opacity: 0;
          }
        }
        .item-img{
          width: 25%;
          overflow: hidden;
          text-align: center;
          img{
            height:60px;
            width:60px;
            /*margin-top: 10px;*/
          }
        }
        .item-text{
          width: 65%;
          float: left;
          .name{
            width: 100%;
            line-height:20px;
            /*height:40px;*/
            display: flex;
            justify-content: space-between;
            .name-left{
              width: 80%;
              label{
                font-weight: 700;
              }
              p{
                color:#999;
                font-size: 0.6rem;
              }
            }
            .name-right{
              width: 20%;
              text-align: center;
              font-size:1rem;
              color:#ccc;
            }
          }
          .name-bottom{
            display: flex;
            justify-content: space-between;
            .price{
              color: #ff0000;
              font-weight: 700;
              line-height:30px;
              span{
                font-size: 1rem;
              }
            }
            .num{
            }
          }
        }
      }
    }
    .clearCart{
      float: right;cursor: pointer;
      &:hover{
        color: red;
      }
    }
  }
  .bottomCalc{
    position: fixed;
    width: 100%;
    left: 0;
    bottom: 3.15rem;
    border-top: 1px solid #eee;
    padding-left: 1rem;
    line-height: 48px;
    display: flex;
    justify-content: space-between;
    box-sizing: border-box;
    background: #fff;
    .cal{
      .calc{
        color: #ff0000;
        font-weight: 700;
        padding-right:1rem;
      }
      .btn{
        height:100%;
        padding: 0 1rem;
        background: #33bb99;
        color:#fff;
        display: inline-block;
        letter-spacing: 0.2rem;
      }
    }
  }
</style>
